<template>
  <div>
    <p class="con-title">
      <span>
        <img src="@/assets/img/control/content/Group769.png" />
      </span>
      <span>云服务器</span>
    </p>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane :label="'所有' + all" name="0" />
      <el-tab-pane :label="'运行中' + normal" name="ACTIVE" />
      <el-tab-pane :label="'已停止' + due" name="SHUTOFF" />
      <el-tab-pane :label="'已删除' + Expired" name="DELETED" />
      <el-tab-pane :label="'已到期' + stopped" name="EXPIRED" />
    </el-tabs>

    <el-table :data="lieList" header-cell-class-name="title-style" border>
      <el-table-column prop="relationId" label="主机号" align="center" show-overflow-tooltip/>
      <el-table-column prop="remark" label="云服务器描述" align="center" show-overflow-tooltip>
        <template #default="scope">
          <div v-if="!scope.row.isEdit">
            <span>{{ scope.row.remark }}</span>
            <el-icon @click="scope.row.isEdit = true"><Edit /></el-icon>
          </div>
          <div style="display: flex;align-items: center;" v-else>
            <el-input type="text" v-model="scope.row.remark"></el-input>
            <el-icon @click="doChangeRemark(scope.row)" color="green"><Select /></el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="periodType" label="计费模式" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ cPeriodType(scope.row.periodType) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="regionId" label="地区" align="center" show-overflow-tooltip/>
      <el-table-column prop="ip" label="IP" align="center" show-overflow-tooltip/>
      <el-table-column prop="orderAbstract" label="配置（CPU | 内存 | 硬盘 | 带宽）" align="center" show-overflow-tooltip/>
      <el-table-column prop="expirationTime" label="到期时间" align="center" show-overflow-tooltip/>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-tag class="ml-2" :type="cTag(scope.row.status)">{{ cStatus(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="open(scope.row)">开机</el-button>
          <el-button type="danger" link @click="close(scope.row)">关机</el-button>
          <el-button type="warning" link @click="openAgain(scope.row)">重启</el-button>
          <el-button type="success" link @click="renew(scope.row)">续费</el-button>
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="resetPwd(scope.row)">重置密码</el-dropdown-item>
                <el-dropdown-item @click="toChange(scope.row)">变更</el-dropdown-item>
                <el-dropdown-item @click="switchSystem(scope.row)">切换系统</el-dropdown-item>
                <el-dropdown-item @click="reinstallSystem(scope.row)">重装系统</el-dropdown-item>
                <el-dropdown-item @click="buySame(scope.row)">购买相同配置</el-dropdown-item>
                <el-dropdown-item @click="remoteLogin(scope.row)">远程登录</el-dropdown-item>
                <el-dropdown-item @click="doSafeRules(scope.row)">安全规则配置</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination :total="total" v-model:current-page="queryParams.params.pageNum"
      v-model:page-size="queryParams.params.pageSize" layout="->,total, prev, pager, next" small @size-change="getList"
      @current-change="getList" />

    <!-- 重启 -->
    <el-dialog v-model="isOpenAgain" title="重启">
      <el-form :model="openAgainForm" :rules="openAgainRules" ref="openAgainFormRef">
        <el-descriptions title="确定要对以下1台云服务器进行重启操作吗？" direction="vertical" :column="3" border>
          <el-descriptions-item label="名称">{{ openAgainForm.relationId }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag class="ml-2" :type="cTag(openAgainForm.status)">{{ cStatus(openAgainForm.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注">{{ cPeriodType(openAgainForm.periodType) }}</el-descriptions-item>
        </el-descriptions>
        <el-form-item label="重启方式" prop="type">
          <el-radio-group v-model="openAgainForm.type">
            <el-radio label="HARD">强制重启</el-radio>
            <el-radio label="SOFT">普通重启</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <p class="notice">强制重启会导致云服务器中未保存的数据丢失，请谨慎操作。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="openAgainReset(openAgainFormRef)">取消</el-button>
          <el-button type="primary" @click="openAgainSubmit(openAgainFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 关机 -->
    <el-dialog v-model="isClose" title="关机">
      <el-form :model="closeForm" :rules="closeRules" ref="closeFormRef">
        <el-descriptions title="确定要对以下1台云服务器进行关机操作吗？" direction="vertical" :column="3" border>
          <el-descriptions-item label="名称">{{ closeForm.relationId }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag class="ml-2" :type="cTag(closeForm.status)">{{ cStatus(closeForm.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注">{{ cPeriodType(closeForm.periodType) }}</el-descriptions-item>
        </el-descriptions>
        <el-form-item label="关机方式" prop="type">
          <el-radio-group v-model="closeForm.type">
            <el-radio label="HARD">强制关机</el-radio>
            <el-radio label="SOFT">普通关机</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <p class="notice">强制关机会导致云服务器中未保存的数据丢失，请谨慎操作。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeReset(closeFormRef)">取消</el-button>
          <el-button type="primary" @click="closeSubmit(closeFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码 -->
    <el-dialog v-model="isResetPwd" title="重置密码">
      <p class="resetPwd">弹性云服务器重启后，新密码自动生效</p>
      <p class="checkOneNotice">您已选1台云服务器，其中1台可重置密码。展开</p>
      <el-form :model="resetPwdForm" :rules="resetPwdRules" ref="resetPwdFormRef" label-width="100px"
        label-position="left">
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="resetPwdForm.newPwd" type="password" placeholder="密码长度为8-26位,且包含大写字母，小写字母，数字，特殊符号至少三种"
            show-password />
        </el-form-item>
        <el-form-item label="确认新密码" prop="pwdAgain">
          <el-input v-model="resetPwdForm.pwdAgain" type="password" placeholder="密码长度为8-26位,且包含大写字母，小写字母，数字，特殊符号至少三种"
            show-password />
        </el-form-item>
        <el-form-item label="自动重启" prop="type">
          <el-checkbox-group v-model="resetPwdForm.type">
            <el-checkbox label="运行中的云服务器，需重启后新密码才可生效" name="type" />
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <p class="notice">自动重启可能会导致数据丢失，建议您先关机再重置密码。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPwdFormReset(resetPwdFormRef)">取消</el-button>
          <el-button type="danger" @click="resetPwdFormSubmit(resetPwdFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 续费 -->
    <el-dialog v-model="isRenew" title="续费">
      <el-form :model="renewForm" :rules="renewRules" ref="renewFormRef">
        <el-descriptions title="确定要对以下1台云服务器进行续费操作吗？" direction="vertical" :column="3" border>
          <el-descriptions-item label="名称">{{ renewForm.relationId }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag class="ml-2" :type="cTag(renewForm.status)">{{ cStatus(renewForm.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注">{{ cPeriodType(renewForm.periodType) }}</el-descriptions-item>
        </el-descriptions>
        <el-form-item label="续费选择" prop="renewTypeNum" style="margin-top: 20px">
          <el-cascader :options="cperiodNumOptions" v-model="renewForm.renewTypeNum" @change="renewTypeNumChange" />
        </el-form-item>
      </el-form>
      <p>续费金额是：<span style="color: red;font-size: 16px;">￥{{ renewPrice }}</span></p>
      <p class="notice">强制关机会导致云服务器中未保存的数据丢失，请谨慎操作。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renewReset(renewFormRef)">取消</el-button>
          <el-button type="primary" @click="renewSubmit(renewFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 切换系统 -->
    <el-dialog v-model="isSwitchSystem" title="切换系统" width="60vw">
      <div class="reinstall-system-box">
        <p>切换操作系统提供以用户选择的镜像进行重装系统的功能。</p>
        <p style="color: red">1、切换操作系统不影响数据盘数据，但是系统盘的所有分区数据和创建的所有快照会被删除，请做好数据备份。</p>
        <p style="color: red">2、部分操作系统不支持挂载SCSI磁盘，切换操作系统后，可能会导致原弹性云服务器上挂载的SCSI磁盘不可用。查看支持列表</p>
        <p>3、切换操作系统成功后，云服务器会自动开机;当前操作系统内的个性化设置(如DNS、主机名等）将被重置，需重新配置</p>
      </div>

      <el-descriptions title="当前配置" direction="vertical" :column="4" border class="descriptions">
        <el-descriptions-item label="主机号">{{ switchSystemForm.relationId }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ switchSystemIP }}</el-descriptions-item>
        <el-descriptions-item label="规格">{{ switchSystemObj.flavor?.id }}|{{ switchSystemObj.flavor?.vcpus
        }}vCPUs</el-descriptions-item>
        <el-descriptions-item label="镜像">{{ switchSystemObj.metadata?.image_name }}</el-descriptions-item>
      </el-descriptions>

      <el-form :model="switchSystemForm" :rules="switchSystemRules" ref="switchSystemFormRef" label-width="100px"
        label-position="left">
        <el-form-item label="镜像" prop="newPwd">
          <div>
            <el-radio-group v-model="imageType">
              <el-radio-button label="1">公共镜像</el-radio-button>
            </el-radio-group>
            <div class="chooseSystem">
              <el-select v-model="systemValue" class="m-2" placeholder="请选择操作系统" size="large" @change="changeSystemValue">
                <el-option v-for="item in systemOption" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <span style="margin-right:20px"></span>
              <el-select v-model="systemVersion" class="m-2" placeholder="请选择操作系统版本" size="large"
                @change="changeSystemVersion">
                <el-option v-for="item in systemVersionOption" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="switchSystemReset(switchSystemFormRef)">取消</el-button>
          <el-button type="danger" @click="switchSystemSubmit(switchSystemFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重装系统 -->
    <el-dialog v-model="isReinstallSystem" title="重装系统" width="70vw">
      <div class="reinstall-system-box">
        <p>重装操作系统提供以原镜像进行系统重装的功能，不会收取额外费用。</p>
        <p style="color: red;">1、重装系统不影响数据盘数据，但是系统盘的所有分区数据和创建的所有快照会被删除，请做好数据备份。</p>
        <p>2、重装系统成功后，云服务器会自动开机;当前操作系统内的个性化设置(如DNS、主机名等）将被重置，需重新配置</p>
      </div>

      <el-descriptions title="当前配置" direction="vertical" :column="4" border class="descriptions">
        <el-descriptions-item label="云服务器名称">{{ reinstallSystemObj.name }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ reinstallSystemIP }}</el-descriptions-item>
        <el-descriptions-item label="规格">{{ reinstallSystemObj.flavor.id }}|{{ reinstallSystemObj.flavor.vcpus
        }}vCPUs</el-descriptions-item>
        <el-descriptions-item label="镜像">{{ reinstallSystemObj.metadata['image_name'] }}</el-descriptions-item>
      </el-descriptions>

      <el-form :model="reinstallSystemForm" :rules="reinstallSystemRules" ref="reinstallSystemFormRef" label-width="100px"
        label-position="left">
        <el-form-item label="密码" prop="newPwd">
          <el-input v-model="reinstallSystemForm.newPwd" type="password" placeholder="密码长度为8-26位,且包含大写字母，小写字母，数字，特殊符号至少三种"
            show-password />
          <p>可使用云服务器原密码或重新设置密码，请输入并牢记密码。</p>
        </el-form-item>
        <el-form-item label="确认密码" prop="newPwdAgain">
          <el-input v-model="reinstallSystemForm.newPwdAgain" type="password"
            placeholder="密码长度为8-26位,且包含大写字母，小写字母，数字，特殊符号至少三种" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reinstallSystemReset(reinstallSystemFormRef)">取消</el-button>
          <el-button type="danger" @click="reinstallSystemSubmit(reinstallSystemFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 安全组规则配置  -->
    <el-dialog v-model="isSafe" title="重启" width="700px">
      <el-form :model="safeForm" :rules="safeRules" ref="safeFormRef" label-width="100px" label-position="left">
        <el-form-item label="云服务器ID" prop="relationId">
          <p>{{ safeForm.relationId }}</p>
        </el-form-item>
        <!-- <el-form-item label="网卡" prop="">
          <el-select v-model="safeForm.wangka" placeholder="请选择网卡">
            <el-option v-for="item in networkCarkList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="安全组" prop="name">
          <el-input v-model="safeForm.name" placeholder="请输入安全组完整名称" clearable>
            <template #append>
              <span @click="getSafeList">查询</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="" prop="">
          <el-table :data="safeList" header-cell-class-name="title-style" border>
            <el-table-column prop="name" label="安全组名称" align="center" />
            <el-table-column prop="description" label="描述" align="center" show-overflow-tooltip />
            <el-table-column label="操作" width="200" align="center">
              <template #default="scope">
                <el-button type="primary" link @click="toSafeRules(scope.row)">配置规则</el-button>
                <el-button type="danger" link @click="toDelSafeRules(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="safeReset(safeFormRef)">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { relationList, statisticsStatus } from '@/api/control/order'
import { cPeriodType, cStatus, cTag } from '@/utils/filter';
import { ElMessage, ElMessageBox } from 'element-plus';
import { openServers, closeServers, openServersAgain, resetPassword, renewalResources, buyAgain, reinstallServerWithCloudInit, glanceListImages, changeServerOsWithCloudInit, showServerRemoteConsole, safeGroupsList, delSafeGroups, changeRemark } from '@/api/control/myServer';
import { shoppingCar } from "@/api/cloud/index";
import type { FormInstance } from 'element-plus';
import { useRouter } from "vue-router";
const router = useRouter();
const activeName = ref<any>('0')
const all = ref('(0)')
const normal = ref('(0)')
const due = ref('(0)')
const Expired = ref('(0)')
const stopped = ref('(0)')
const total = ref(0)
//表格数据
const lieList = ref<any>([]);
//重启弹窗开关
const isOpenAgain = ref(false);
//重启表单数据
const openAgainForm = ref<any>({});
//请求参数
const queryParams = ref<any>({
  searchValue: null,
  status: null,
  params: {
    pageNum: 1,
    pageSize: 10,
  },
});

onMounted(() => {
  getList();
  statusTotal();
})

//获取表格数据
const getList = () => {
  relationList(queryParams.value).then((res: any) => {
    lieList.value = res.rows
    lieList.value.forEach((item: any) => {
      item.isEdit = false
    });
    total.value = res.total
  })
}

//修改云服务器描述
const doChangeRemark = (row: any) => {
  row.isEdit = false;
  changeRemark({id: row.id, remark: row.remark}).then((res: any) => {
    if (200 == res.code) {
      ElMessage.success('修改成功！')
    }
  })
}

//统计状态总数
const statusTotal = () => {
  statisticsStatus({}).then((res: any) => {
    const data = res.data;
    normal.value = `(${getTotal(data, 'ACTIVE') || 0})`
    due.value = `(${getTotal(data, 'SHUTOFF') || 0})`
    Expired.value = `(${getTotal(data, 'DELETED') || 0})`
    stopped.value = `(${getTotal(data, 'EXPIRED') || 0})`
    all.value = `(${getTotal(data, 'ACTIVE') + getTotal(data, 'SHUTOFF') + getTotal(data, 'DELETED') + getTotal(data, 'EXPIRED')})`
  })
}

//获取每个状态的总数
const getTotal = (arr: any, type: any) => {
  return arr.find((item: any) => item.status == type)?.count || 0
}
//切换状态
const handleClick = (tab: any, event: Event) => {
  queryParams.value.status = tab.paneName == '0' ? null : tab.paneName;
  getList();
}

//开机
const open = (val: any) => {
  ElMessageBox.confirm(
    `确定要对${val.relationId}云服务器进行开机操作吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      customClass: 'myClass',
      'close-on-click-modal': false,
      type: 'warning',
    }
  )
    .then(() => {
      openServers({
        'os-start': {
          servers: [{ id: val.relationId }]
        }
      }).then((res: any) => {
        if (200 == res.code) {
          getList()
          ElMessage({
            type: 'success',
            message: '开机成功！'
          })
        }
      })

    })
    .catch(() => { })
}

//重启====================================================================================================
//打开重启对话框
const openAgain = (val) => {
  isOpenAgain.value = true;
  openAgainForm.value = val;
}
//表单验证
const openAgainFormRef = ref<FormInstance>()
const openAgainRules = reactive({
  type: [
    { required: true, message: '请选择重启方式', trigger: 'change' }
  ]
})
//提交表单
const openAgainSubmit = async (formEl: any) => {
  if (!formEl) return
  await formEl.validate((valid: boolean) => {
    if (valid) {
      openServersAgain({
        reboot: {
          servers: [{ id: openAgainForm.value.relationId }],
          type: openAgainForm.value.type
        }
      }).then((res: any) => {
        if (200 == res.code) {
          getList();
          isOpenAgain.value = false;
          ElMessage.success('重启成功！')
        }
      })
    }
  })
}

//取消重启表单
const openAgainReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  isOpenAgain.value = false;
}

//关机=============================================================================================================
//打开关机对话框
const closeForm = ref<any>({ type: 'SOFT' });
const isClose = ref(false);
const close = (val: any) => {
  isClose.value = true;
  closeForm.value = val;
}
//表单验证
const closeFormRef = ref<FormInstance>()
const closeRules = reactive<any>({
  type: [{ required: true, message: '请选择关机方式', trigger: 'change' }]
})
//提交表单
const closeSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      closeServers({
        "os-stop": {
          servers: [{ id: closeForm.value.relationId }],
          type: closeForm.value.type
        }
      }).then((res: any) => {
        if (200 == res.code) {
          getList()
          isClose.value = false;
          ElMessage.success('关机成功！')
        }
      })
    }
  })
}

//取消关机表单
const closeReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  isClose.value = false;
}

//重置密码=============================================================================================================
const isResetPwd = ref(false);
const resetPwdForm = ref<any>({});
//打开重置密码对话框
const resetPwd = (val: any) => {
  isResetPwd.value = true;
  resetPwdForm.value = val;
}
//表单验证
const resetPwdFormRef = ref<FormInstance>()
const resetPwdRules = reactive<any>({
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'change' }
  ],
  pwdAgain: [
    { required: true, message: '请输确认密码', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请勾选', trigger: 'change' }
  ],
})
//提交表单
const resetPwdFormSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid: boolean) => {
    if (valid) {
      if (resetPwdForm.value.newPwd == resetPwdForm.value.pwdAgain) {
        const data = {
          new_password: resetPwdForm.value.newPwd,
          servers: [{ id: resetPwdForm.value.relationId }]
        }
        resetPassword(data).then((res: any) => {
          if (200 == res.code) {
            getList();
            isResetPwd.value = false;
            ElMessage.success('重置密码成功')
          }
        })
      } else {
        ElMessage.info('两次密码不一致')
      }
    }
  })
}

//取消重置表单
const resetPwdFormReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  isResetPwd.value = false;
}

//续费========================================================================================================
import { payBtn } from "@/api/pay/pay";//查询价格接口

//打开续费对话框
const isRenew = ref(false);
const renewForm = ref<any>({});
const renewPrice = ref(0);//续费的金额
const priceKey = ref('');//续费查价返回的key，加入购物车是需要的参数
const getPriceData = ref<any>({});//查询价格的参数
//续费选择的级联数据
const cperiodNumOptions = <any>[
  {
    value: '2',
    label: '包月',
    children: [
      { value: '1', label: '1个月' },
      { value: '2', label: '2个月' },
      { value: '3', label: '3个月' },
      { value: '4', label: '4个月' },
      { value: '5', label: '5个月' },
      { value: '6', label: '6个月' },
      { value: '7', label: '7个月' },
      { value: '8', label: '8个月' },
      { value: '9', label: '9个月' },
      { value: '10', label: '10个月' },
      { value: '11', label: '11个月' }
    ]
  },
  {
    value: '3',
    label: '包年',
    children: [
      { value: '1', label: '1年' },
      { value: '2', label: '2年' },
      { value: '3', label: '3年' }
    ]
  }
]
//打开续费对话框
const renew = (val: any) => {
  isRenew.value = true;
  renewForm.value = val;
  getPriceData.value = JSON.parse(val.priceQueryJsonStr);
}

//选择计费时间
const renewTypeNumChange = (e: any) => {
  const product_infos = getPriceData.value.product_infos.map(item => {
    return {
      ...item,
      period_type: e ? e[0] : null,
      period_num: e ? e[1] : null,
    }
  })
  getPriceData.value.product_infos = product_infos;
  renewGetPrice(getPriceData.value);
};

//查询价格
const renewGetPrice = (data: any) => {
  payBtn(data).then((res: any) => {
    if (200 == res.code) {
      renewPrice.value = res.data.price;
      priceKey.value = res.data.priceKey;
    }
  })
};
//表单验证
const renewFormRef = ref<FormInstance>()
const renewRules = reactive<any>({})
//提交表单
const renewSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      renewGoShoppingCar(renewForm.value.id, renewForm.value.renewTypeNum[1], renewForm.value.renewTypeNum[0]);
    }
  })
}

//加入购物车
const renewGoShoppingCar = (id, period_num, period_type) => {
  const jsonStr = JSON.stringify({ id, period_num, period_type });
  shoppingCar({ jsonStr, shoppingCarEnums: 'CLOUD_SERVER_RENEW', originalPrice: renewPrice.value, priceKey: priceKey.value }).then((res: any) => {
    if (200 == res.code) {
      isRenew.value = false;
      router.push("/control/order/myShoppingCart");
    }
  })
}
//取消续费表单
const renewReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  isRenew.value = false
}

//变更==============================================================================================================
const toChange = (row: any) => {
  router.push(`/control/myServer/change?chooseId=${row.id}&regionId=${row.regionId}&id=${row.id}`);
}

//切换系统==============================================================================================================
const isSwitchSystem = ref(false);
const switchSystemForm = ref<any>({});
const imageType = ref(1);
const switchSystemObj = ref<any>({});
const switchSystemIP = ref('');
const allSystem = ref<any>([]);
const systemValue = ref('');//选择操作系统的值
const systemOption = ref<any>([]);//选择操作系统选项的数据
const systemVersion = ref('');// 选择操作系统版本的值 
const systemVersionOption = ref<any>([]);//选择操作系统版本选项的数据
//打开切换系统对话框
const switchSystem = (val: any) => {
  isSwitchSystem.value = true;
  switchSystemForm.value = val;
  switchSystemObj.value = JSON.parse(val.serversJsonStr);
  switchSystemIP.value = val.ip;
  getImageList();
}
//获取镜像列表
const getImageList = () => {
  const data = {
    "__imagetype": "gold",
    "status": "active",
    "__support_kvm": true,
    "virtual_env_type": "FusionCompute"
  }
  glanceListImages(data).then((res: any) => {
    if (200 == res.code) {
      allSystem.value = res.data.images.reduce((data, item) => {
        return [
          ...data,
          {
            label: item.name,
            value: item.id,
            __platform: item.__platform
          }
        ]
      }, [])
    };
    allSystem.value.sort();
    let systemOptions = [res.data.images[0]];
    for (let i = 1; i < res.data.images.length; i++) {
      if (res.data.images[i].__platform !== res.data.images[i - 1].__platform) {
        systemOptions.push(res.data.images[i]);
      }
    }
    systemOption.value = systemOptions.reduce((data, item) => {
      return [
        ...data,
        {
          label: item.__platform,
          value: item.__platform
        }
      ]
    }, [])
  })
}

//切换操作系统
const changeSystemValue = (e: any) => {
  systemVersionOption.value = allSystem.value.filter((item: any) => item.__platform === e);
  systemVersion.value = systemVersionOption.value[0].value;
}

//切换操作系统版本
const changeSystemVersion = (e: any) => {
  console.log(e, '操作系统版本');
}

//表单验证
const switchSystemFormRef = ref<FormInstance>()
const switchSystemRules = reactive<any>({})
//提交表单
const switchSystemSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      const data = {
        regionId: switchSystemForm.value.regionId,
        server_id: switchSystemForm.value.relationId,
        body: {
          "os-change": {
            imageid: systemVersion.value
          }
        }
      }
      changeServerOsWithCloudInit(data).then((res: any) => {
        if (200 == res.code) {
          getList();
          isSwitchSystem.value = false;
          ElMessage.success(res.msg);
        }

      })
    }
  })
}
//取消切换表单
const switchSystemReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  isSwitchSystem.value = false
}

//重装系统 ==============================================================================================================
const isReinstallSystem = ref<any>(false);
const reinstallSystemForm = ref<any>({});
const reinstallSystemObj = ref<any>({});//当前配置
const reinstallSystemIP = ref('');
//打开变更对话框
const reinstallSystem = (val: any) => {
  isReinstallSystem.value = true;
  reinstallSystemForm.value = val;
  reinstallSystemObj.value = JSON.parse(val.serversJsonStr);
  reinstallSystemIP.value = val.ip;
}
//表单验证
const reinstallSystemFormRef = ref<FormInstance>()
const reinstallSystemRules = reactive<any>({})
//提交表单
const reinstallSystemSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      const data = {
        server_id: reinstallSystemForm.value.relationId,
        body: {
          'os-reinstall': {
            adminpass: reinstallSystemForm.value.newPwd
          }
        }
      };
      if (reinstallSystemForm.value.newPwd == reinstallSystemForm.value.newPwdAgain) {
        const isTrue = /^(?![\da-z]+$)(?![\dA-Z]+$)(?![\d!@\$%\^-_=\+\[\{\}\]\:,\.\/\?~#*]+$)(?![a-zA-Z]+$)(?![a-z!@\$%\^-_=\+\[\{\}\]\:,\.\/\?~#*]+$)(?![A-Z!@\$%\^-_=\+\[\{\}\]\:,\.\/\?~#*]+$)[\da-zA-z!@\$%\^-_=\+\[\{\}\]\:,\.\/\?~#*]{8,26}$/.test(reinstallSystemForm.value.newPwd);
        if (isTrue) {
          reinstallServerWithCloudInit(data).then((res: any) => {
            if (200 == res.code) {
              getList();
              isReinstallSystem.value = false;
              ElMessage.success('重装系统成功');
            }
          })
        } else {
          ElMessage.info('密码格式不正确');
        }
      } else {
        ElMessage.info('两次密码不一致');
      }
    }
  })
}
//取消重装表单
const reinstallSystemReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  isReinstallSystem.value = false
}

//购买相同配置 ==============================================================================================================
const buySame = (val: any) => {
  ElMessageBox.confirm(
    `确定购买与该云服务器相同的配置吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      customClass: 'myClass',
      closeOnClickModal: false,
      type: 'warning',
    }
  )
    .then(() => {
      buyAgain(val.id).then((res: any) => {
        if (200 == res.code) {
          getList()
          ElMessage.success('购买成功！')
        }
      })
    })
    .catch(() => { })
}
//远程登录================================================================================================================
const remoteLogin = (row: any) => {
  const data = {
    server_id: row.relationId,
    body: {
      remote_console: {
        protocol: "vnc",
        type: "novnc"
      }
    }
  }
  showServerRemoteConsole(data).then((res: any) => {
    if (200 == res.code) {
      const url = res.data.remote_console.url;
      let alink = document.createElement("a");
      alink.href = url;
      alink.click();
      alink.remove();
    }
  })
}

//安全规则配置===================================================================================================
const isSafe = ref(false); //安全组对话框开关
const safeForm = ref<any>({}); //安全组规则配置表单
const safeList = ref<any>([]);//安全组的数组

const doSafeRules = (val: any) => {
  isSafe.value = true;
  safeForm.value = val;
  getSafeList();
}

//获取安全组列表数据
const getSafeList = () => {
  const data = {
    regionId: "",
    body: {
      limit: 100,
      name: safeForm.value.name
    }
  };
  safeGroupsList(data).then((res: any) => {
    if (200 == res.code) {
      safeList.value = res.data.security_groups;
    }
  })
};

//跳转到配置安全规则页面
const toSafeRules = (row: any) => {
  router.push(`/control/myServer/safeGroups?id=${row.id}`)
};

//删除安全组
const toDelSafeRules = (row: any) => {
  ElMessageBox.confirm(
    `确定删除${row.name}安全组吗?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const data = {
        regionId: "",
        body: {
          security_group_id: row.id
        }
      };
      delSafeGroups(data).then((res: any) => {
        if (200 == res.code) {
          getSafeList();
          ElMessage.success(`删除安全组${row.name}成功！`)
        }
      })
    })
    .catch(() => { })
};

//表单验证
const safeFormRef = ref<FormInstance>()
const safeRules = reactive({
  type: [
    { required: true, message: '请选择重启方式', trigger: 'change' }
  ]
})

//取消安全配置表单
const safeReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  isSafe.value = false;
};
</script>

<style>
.myClass {
  z-index: 3000 !important;
  position: absolute;
  left: 40vw;
}
</style>
<style lang="less" scoped>
.title-style {
  height: 60px;
  background-color: #f6faff !important;
}

.chooseSystem {
  margin-top: 20px;
}

.checkOneNotice {
  margin-bottom: 20px;
}

.resetPwd {
  height: 40px;
  line-height: 40px;
  border: 1px solid #c5daf4;
  background-color: #e8f3ff;
  margin-bottom: 20px;
  text-indent: 32px;
}

.notice {
  background-color: rgb(251, 240, 232);
  // height: 40px;
  padding: 4px 0;
  line-height: 40px;
  border: 1px solid #ff6e40;
  text-indent: 16px;
  margin-top: 10px;
}

.con-title {
  width: 100%;
  height: 25px;
  display: flex;
  align-items: center;

  span:nth-child(1) {
    display: flex;
    align-items: center;

    img {
      width: 14px;
      height: 14px;
    }
  }

  span:nth-child(2) {
    display: flex;
    align-items: center;
    margin-left: 10px;
    font-size: 16px;
  }
}

.reinstall-system-box {
  background-color: #def2ff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-bottom: 20px;
  padding: 20px 20px;
}

.descriptions {
  margin-bottom: 20px;
}
</style>
